package com.foreveross.fetl.queue.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dayatang.domain.InstanceFactory;
import com.foreveross.fetl.application.IExchangeRateApplication;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.PriceUtil;
import com.foreveross.fetl.vo.ExchangeRateVO;

public class ExchangeRateUtil {
	
private static Map<String,Double> refePriceMap=new HashMap<String,Double>();
	
	public static Map<String,Double> getRefePriceMap(){
		if(null==refePriceMap){
			refePriceMap=new HashMap<String,Double>();
		}
		return refePriceMap;
	}
	
	/**
	 * 初始化汇率，从表里读取最新汇率
	 * @param date yyyyMMdd 
	 */
	public static void initExchangeRate(String date){
		getRefePriceMap().clear();//先清空
		List<String> listName =new ArrayList<String>();
		Collections.addAll(listName, "HKD","USD","EUR","JPY","KRW");
		for(String code: listName){
			initExchangeRate(code, date);
		}
		getRefePriceMap().put("CNH", 1d);
		getRefePriceMap().put("CNY", 1d);
		getRefePriceMap().put("RMB", 1d);
		getRefePriceMap().put(null, 1d);
	}
	

	
	/**
	 * 
	 * @param code CNY
	 * @param date yyyyMMdd 
	 */
	public static void initExchangeRate(String code,String date){
		if(code==null || "".equalsIgnoreCase(code)){
			return;
		}
		IExchangeRateApplication exchangeRateApplication=InstanceFactory.getInstance(IExchangeRateApplication.class);
		List<ExchangeRateVO> list =null;
		 list =exchangeRateApplication.findByCondition(null, code, date);
		 if(null==list ||  list.isEmpty()){
			 list =exchangeRateApplication.findByCondition(null, code, null);
		 }
		 if(null!=list && list.size()>0){
			 getRefePriceMap().put(code, list.get(0).getRefePrice());
		}
	}
	
	/**
	 * 将价格转换为 人民币  如果数据库里没有对应的税费值 则直接返回 price
	 * @param price 
	 * @param code   USD
	 * @return
	 */
	public static Double conversionPrice(double price,String code){
			
			if(null==code || "".equals(code)) return price;
			return PriceUtil.conversionPrice(price,getRefePrice(code));
	}
	
	/**
	 * 获得税费 如果数据库里没有对应的税费则返回 1 
	 * @param code  如： USD
	 * @return
	 */
	public static Double getRefePrice(String code){
		if(null==code){
			return 1d;
		}
		if(!getRefePriceMap().containsKey(code)){
			initExchangeRate( code,DateUtils.format(new Date(), "yyyyMMdd"));
		}
		Double refePrice=getRefePriceMap().get(code);
		if(null==refePrice || refePrice==0 || refePrice<0) {
			return 1d;
		}
		return refePrice;
	}
	

}
